/****************************************************
	文件：ABLoader.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/12/20 18:5:6
	功能：AssetBundle 加载器
*****************************************************/

using System;
using HTFW.Core;
using HTFW.Logger;

namespace HTFW.Res
{
    public class ABLoader : IResLoader
    {
        public int ObjectPoolIndex { get; set; }

        public void Dispose()
        {
        }

        public void LoadSync(ResData abRes) //暂时不需要使用此方法
        {
            if (abRes.ResType != ResType.AssetBundle) return;
        }

        public ILoadResult LoadAsync(ResData abRes, Action onCompleted)
        {
            if (abRes.ResType != ResType.AssetBundle) return null;

            if (abRes.LoadState == ResLoadState.Loading) //加载正在加载的资源
            {
                abRes.LoadState = ResLoadState.Loading;

                abRes.OnAsyncLoadDone += () =>
                {
                    abRes.IncreaseRef();

                    onCompleted?.Invoke();

                    ResClassObjectPool.Instance.DespawnABLoader(this);
                };
            }
            else if (abRes.LoadState == ResLoadState.Loaded)
            {
                HLog.Error($"LoadAsync error! 资源 abName：{abRes.ABName} 已加载");
            }
            else
            {
                abRes.LoadState = ResLoadState.Loading;

                abRes.OnAsyncLoadDone = () =>
                {
                    abRes.IncreaseRef();
                    ResCache.Instance.Add(abRes.ABName, abRes);

                    abRes.LoadState = ResLoadState.Loaded;

                    onCompleted?.Invoke();

                    ResClassObjectPool.Instance.DespawnABLoader(this);
                };
                //TODO 加载 AssetBundle
                ResScheduler.Instance.AddResCommand(abRes);
            }

            return null;
        }
    }
}